<!--<!DOCTYPE html>-->
<!--<html lang="zh-CN">-->
<!--<head>-->
<!--    <meta charset="UTF-8">-->
<!--    <meta name="viewport" content="width=device-width, initial-scale=1.0">-->
<!--    <title>图书馆座位预约系统 - 座位选择</title>-->
<!--    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">-->
<!--    <style>-->
<!--        * {-->
<!--            margin: 0;-->
<!--            padding: 0;-->
<!--            box-sizing: border-box;-->
<!--            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;-->
<!--        }-->
<!--        body {-->
<!--            background-color: #f0f8ff;-->
<!--            min-height: 100vh;-->
<!--            color: #333;-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--        }-->
<!--        .container {-->
<!--            max-width: 1200px;-->
<!--            margin: 0 auto;-->
<!--            padding: 20px;-->
<!--            flex: 1;-->
<!--        }-->
<!--        .main-header {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);-->
<!--            padding: 15px 0;-->
<!--        }-->
<!--        .header-container {-->
<!--            max-width: 1200px;-->
<!--            margin: 0 auto;-->
<!--            padding: 0 20px;-->
<!--            display: flex;-->
<!--            justify-content: space-between;-->
<!--            align-items: center;-->
<!--        }-->
<!--        .logo {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 10px;-->
<!--            font-size: 1.5rem;-->
<!--            font-weight: bold;-->
<!--            color: #1a2a6c;-->
<!--        }-->
<!--        .main-nav ul {-->
<!--            display: flex;-->
<!--            list-style: none;-->
<!--            gap: 20px;-->
<!--        }-->
<!--        .main-nav a {-->
<!--            text-decoration: none;-->
<!--            color: #333;-->
<!--            padding: 8px 15px;-->
<!--            border-radius: 5px;-->
<!--            transition: background-color 0.3s;-->
<!--        }-->
<!--        .main-nav a:hover, .main-nav li.active a {-->
<!--            background-color: #1a73e8;-->
<!--            color: white;-->
<!--        }-->
<!--        .user-info {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 15px;-->
<!--        }-->
<!--        .welcome {-->
<!--            font-weight: 500;-->
<!--        }-->
<!--        .main-content {-->
<!--            flex: 1;-->
<!--            padding: 20px 0;-->
<!--        }-->
<!--        .selection-header {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--            margin-bottom: 30px;-->
<!--        }-->
<!--        .selection-header h1 {-->
<!--            color: #1a2a6c;-->
<!--            margin-bottom: 20px;-->
<!--            font-size: 2rem;-->
<!--        }-->
<!--        .time-selector label {-->
<!--            font-weight: 500;-->
<!--            color: #1a2a6c;-->
<!--            font-size: 1.1rem;-->
<!--        }-->
<!--        .time-grid {-->
<!--            display: grid;-->
<!--            grid-template-columns: repeat(4, 1fr);-->
<!--            gap: 10px;-->
<!--            margin: 15px 0;-->
<!--        }-->
<!--        .time-slot {-->
<!--            padding: 12px 8px;-->
<!--            border: 1px solid #ddd;-->
<!--            border-radius: 5px;-->
<!--            text-align: center;-->
<!--            cursor: pointer;-->
<!--            transition: all 0.2s;-->
<!--            background-color: #f8f9fa;-->
<!--        }-->
<!--        .time-slot:hover {-->
<!--            background-color: #e9ecef;-->
<!--        }-->
<!--        .time-slot.selected {-->
<!--            background-color: #1a73e8;-->
<!--            color: white;-->
<!--            border-color: #1a73e8;-->
<!--        }-->
<!--        .time-slot.disabled {-->
<!--            background-color: #f8f9fa;-->
<!--            color: #adb5bd;-->
<!--            cursor: not-allowed;-->
<!--            opacity: 0.6;-->
<!--        }-->
<!--        .time-summary {-->
<!--            margin-top: 15px;-->
<!--            padding: 15px;-->
<!--            background-color: #f8f9fa;-->
<!--            border-radius: 5px;-->
<!--            text-align: center;-->
<!--        }-->
<!--        .time-summary p {-->
<!--            margin-bottom: 5px;-->
<!--        }-->
<!--        .time-controls button {-->
<!--            padding: 8px 15px;-->
<!--            border: 1px solid #ddd;-->
<!--            border-radius: 5px;-->
<!--            background-color: white;-->
<!--            cursor: pointer;-->
<!--            transition: all 0.2s;-->
<!--        }-->
<!--        .time-controls button:hover {-->
<!--            background-color: #f1f3f4;-->
<!--        }-->
<!--        .floor-selector {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 20px;-->
<!--            margin-bottom: 30px;-->
<!--        }-->
<!--        .floor-tabs {-->
<!--            display: flex;-->
<!--            gap: 10px;-->
<!--            flex-wrap: wrap;-->
<!--        }-->
<!--        .floor-tab {-->
<!--            padding: 12px 20px;-->
<!--            background-color: #f1f3f4;-->
<!--            border: none;-->
<!--            border-radius: 8px;-->
<!--            cursor: pointer;-->
<!--            font-weight: 500;-->
<!--            transition: all 0.3s;-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--            align-items: center;-->
<!--            text-align: center;-->
<!--            min-width: 120px;-->
<!--        }-->
<!--        .floor-tab.active {-->
<!--            background-color: #1a73e8;-->
<!--            color: white;-->
<!--        }-->
<!--        .floor-tab:hover:not(.active) {-->
<!--            background-color: #e0e0e0;-->
<!--        }-->
<!--        .floor-name {-->
<!--            font-size: 1.1rem;-->
<!--            font-weight: 600;-->
<!--        }-->
<!--        .floor-desc {-->
<!--            font-size: 0.85rem;-->
<!--            margin-top: 5px;-->
<!--            opacity: 0.8;-->
<!--        }-->
<!--        .seat-map {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--            margin-bottom: 30px;-->
<!--        }-->
<!--        .map-legend {-->
<!--            display: flex;-->
<!--            gap: 20px;-->
<!--            flex-wrap: wrap;-->
<!--            margin-bottom: 20px;-->
<!--        }-->
<!--        .legend-item {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 8px;-->
<!--        }-->
<!--        .seat-icon {-->
<!--            width: 20px;-->
<!--            height: 20px;-->
<!--            border-radius: 4px;-->
<!--        }-->
<!--        .seat-icon.available {-->
<!--            background-color: #50c878;-->
<!--        }-->
<!--        .seat-icon.occupied {-->
<!--            background-color: #e74c3c;-->
<!--        }-->
<!--        .seat-icon.selected {-->
<!--            background-color: #1a73e8;-->
<!--        }-->
<!--        .seat-icon.in-use {-->
<!--            background-color: #f39c12;-->
<!--        }-->
<!--        .seat-icon.temporary-leave {-->
<!--            background-color: #17a2b8;-->
<!--        }-->
<!--        .seat-grid {-->
<!--            display: flex;-->
<!--            flex-direction: column;-->
<!--            gap: 20px;-->
<!--        }-->
<!--        .map-visualization {-->
<!--            position: relative;-->
<!--            background-color: #f8f9fa;-->
<!--            border-radius: 8px;-->
<!--            padding: 20px;-->
<!--            min-height: 400px;-->
<!--        }-->
<!--        .seats-container {-->
<!--            display: grid;-->
<!--            grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));-->
<!--            gap: 10px;-->
<!--            margin-top: 20px;-->
<!--        }-->
<!--        .seat {-->
<!--            width: 40px;-->
<!--            height: 40px;-->
<!--            border-radius: 6px;-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            justify-content: center;-->
<!--            font-size: 0.8rem;-->
<!--            font-weight: 500;-->
<!--            cursor: pointer;-->
<!--            transition: all 0.2s;-->
<!--            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);-->
<!--        }-->
<!--        .seat.available {-->
<!--            background-color: #50c878;-->
<!--            color: white;-->
<!--        }-->
<!--        .seat.occupied {-->
<!--            background-color: #e74c3c;-->
<!--            color: white;-->
<!--            cursor: not-allowed;-->
<!--        }-->
<!--        .seat.selected {-->
<!--            background-color: #1a73e8;-->
<!--            color: white;-->
<!--            transform: scale(1.1);-->
<!--        }-->
<!--        .seat.in-use {-->
<!--            background-color: #f39c12;-->
<!--            color: white;-->
<!--            cursor: not-allowed;-->
<!--        }-->
<!--        .seat.temporary-leave {-->
<!--            background-color: #17a2b8;-->
<!--            color: white;-->
<!--            cursor: not-allowed;-->
<!--        }-->
<!--        .seat.available:hover:not(.selected) {-->
<!--            background-color: #40b868;-->
<!--            transform: translateY(-2px);-->
<!--        }-->
<!--        .selected-seat-info {-->
<!--            background-color: rgba(255, 255, 255, 0.95);-->
<!--            border-radius: 12px;-->
<!--            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);-->
<!--            padding: 25px;-->
<!--        }-->
<!--        .info-card h3 {-->
<!--            color: #1a2a6c;-->
<!--            margin-bottom: 20px;-->
<!--            font-size: 1.5rem;-->
<!--        }-->
<!--        .seat-details {-->
<!--            background-color: #f8f9fa;-->
<!--            border-radius: 8px;-->
<!--            padding: 20px;-->
<!--            margin-bottom: 20px;-->
<!--        }-->
<!--        .seat-details p {-->
<!--            margin-bottom: 10px;-->
<!--            display: flex;-->
<!--            justify-content: space-between;-->
<!--        }-->
<!--        .seat-details .label {-->
<!--            font-weight: 500;-->
<!--            color: #1a2a6c;-->
<!--        }-->
<!--        .no-seat-selected {-->
<!--            text-align: center;-->
<!--            color: #7f8c8d;-->
<!--            font-style: italic;-->
<!--            padding: 30px 0;-->
<!--        }-->
<!--        .booking-actions {-->
<!--            display: flex;-->
<!--            gap: 15px;-->
<!--        }-->
<!--        .btn {-->
<!--            padding: 12px 25px;-->
<!--            border: none;-->
<!--            border-radius: 5px;-->
<!--            cursor: pointer;-->
<!--            font-weight: 500;-->
<!--            transition: all 0.3s;-->
<!--            flex: 1;-->
<!--            font-size: 1rem;-->
<!--        }-->
<!--        .btn-primary {-->
<!--            background: #1a73e8;-->
<!--            color: white;-->
<!--        }-->
<!--        .btn-primary:hover:not(:disabled) {-->
<!--            background: #0d62d9;-->
<!--        }-->
<!--        .btn-secondary {-->
<!--            background: #f1f3f4;-->
<!--            color: #333;-->
<!--        }-->
<!--        .btn-secondary:hover {-->
<!--            background: #e0e0e0;-->
<!--        }-->
<!--        .btn:disabled {-->
<!--            opacity: 0.6;-->
<!--            cursor: not-allowed;-->
<!--        }-->
<!--        @media (max-width: 768px) {-->
<!--            .header-container {-->
<!--                flex-direction: column;-->
<!--                gap: 15px;-->
<!--            }-->
<!--            .main-nav ul {-->
<!--                flex-wrap: wrap;-->
<!--                justify-content: center;-->
<!--            }-->
<!--            .user-info {-->
<!--                flex-direction: column;-->
<!--                gap: 10px;-->
<!--            }-->
<!--            .selection-controls {-->
<!--                flex-direction: column;-->
<!--                gap: 15px;-->
<!--            }-->
<!--            .time-grid {-->
<!--                grid-template-columns: repeat(2, 1fr);-->
<!--            }-->
<!--            .floor-tabs {-->
<!--                flex-direction: column;-->
<!--            }-->
<!--            .floor-tab {-->
<!--                width: 100%;-->
<!--            }-->
<!--            .seats-container {-->
<!--                justify-content: center;-->
<!--            }-->
<!--            .booking-actions {-->
<!--                flex-direction: column;-->
<!--            }-->
<!--        }-->
<!--        .loading-overlay {-->
<!--            position: absolute;-->
<!--            top: 0;-->
<!--            left: 0;-->
<!--            right: 0;-->
<!--            bottom: 0;-->
<!--            background: rgba(255, 255, 255, 0.8);-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            justify-content: center;-->
<!--            z-index: 1000;-->
<!--            border-radius: 8px;-->
<!--        }-->
<!--        .spinner {-->
<!--            width: 40px;-->
<!--            height: 40px;-->
<!--            border: 4px solid #f3f3f3;-->
<!--            border-top: 4px solid #1a73e8;-->
<!--            border-radius: 50%;-->
<!--            animation: spin 1s linear infinite;-->
<!--        }-->
<!--        @keyframes spin {-->
<!--            0% { transform: rotate(0deg); }-->
<!--            100% { transform: rotate(360deg); }-->
<!--        }-->
<!--        .error-message {-->
<!--            color: #e74c3c;-->
<!--            text-align: center;-->
<!--            padding: 20px;-->
<!--            background: #ffeaea;-->
<!--            border-radius: 5px;-->
<!--            margin: 10px 0;-->
<!--        }-->
<!--        .success-message {-->
<!--            color: #28a745;-->
<!--            text-align: center;-->
<!--            padding: 10px;-->
<!--            background: #e8ffe8;-->
<!--            border-radius: 5px;-->
<!--            margin: 10px 0;-->
<!--            display: none;-->
<!--        }-->
<!--        .floor-info {-->
<!--            display: flex;-->
<!--            justify-content: space-between;-->
<!--            align-items: center;-->
<!--            margin-bottom: 15px;-->
<!--            padding: 10px;-->
<!--            background: #f8f9fa;-->
<!--            border-radius: 5px;-->
<!--        }-->
<!--        .floor-stats {-->
<!--            display: flex;-->
<!--            gap: 15px;-->
<!--            font-size: 0.9rem;-->
<!--        }-->
<!--        .stat-item {-->
<!--            display: flex;-->
<!--            align-items: center;-->
<!--            gap: 5px;-->
<!--        }-->
<!--    </style>-->
<!--</head>-->
<!--<body>-->
<!--<header class="main-header">-->
<!--    <div class="header-container">-->
<!--        <div class="logo"><i class="fa fa-book"></i><span>图书馆座位预约系统</span></div>-->
<!--        <nav class="main-nav">-->
<!--            <ul>-->
<!--                <li><a href="index.html">首页</a></li>-->
<!--                <li class="active"><a href="seat-selection.html">座位选择</a></li>-->
<!--                <li><a href="booking-management.html">预约查询</a></li>-->
<!--                <li><a href="user-profile.html">个人中心</a></li>-->
<!--            </ul>-->
<!--        </nav>-->
<!--        <div class="user-info">-->
<!--            <span class="welcome" id="welcome">欢迎，加载中...</span>-->
<!--            <button class="btn btn-secondary" onclick="logout()" style="margin-left: 10px; padding: 5px 10px; font-size: 0.8rem;">退出</button>-->
<!--        </div>-->
<!--    </div>-->
<!--</header>-->

<!--<main class="main-content">-->
<!--    <div class="container">-->
<!--        <section class="selection-header">-->
<!--            <h1>座位选择</h1>-->
<!--            <div class="selection-controls">-->
<!--                <div class="time-selector">-->
<!--                    <label>选择时间段：</label>-->
<!--                    <div class="time-grid" id="time-grid"></div>-->
<!--                    <div class="time-summary">-->
<!--                        <p class="hint">点击选择开始时间和结束时间</p>-->
<!--                        <p id="time-range-display">已选择：<span id="selected-time">&#45;&#45;:&#45;&#45; - &#45;&#45;:&#45;&#45;</span> 共 <span id="time-duration">0</span> 小时</p>-->
<!--                        <div class="time-controls">-->
<!--                            <button id="clear-time">清空选择</button>-->
<!--                        </div>-->
<!--                    </div>-->
<!--                </div>-->
<!--            </div>-->
<!--        </section>-->

<!--        <section class="floor-selector">-->
<!--            <div class="floor-tabs">-->
<!--                <button class="floor-tab active" data-floor="1"><span class="floor-name">1楼-阅览区</span><span class="floor-desc">400个座位</span></button>-->
<!--                <button class="floor-tab" data-floor="2"><span class="floor-name">2楼-电子阅览区</span><span class="floor-desc">600个座位</span></button>-->
<!--                <button class="floor-tab" data-floor="3"><span class="floor-name">3楼-考公考研区</span><span class="floor-desc">1000个座位</span></button>-->
<!--                <button class="floor-tab" data-floor="4"><span class="floor-name">4楼-阅读区</span><span class="floor-desc">8个座位</span></button>-->
<!--                <button class="floor-tab" data-floor="5"><span class="floor-name">4楼-讨论区</span><span class="floor-desc">300个座位</span></button>-->
<!--            </div>-->
<!--        </section>-->

<!--        <section class="seat-map">-->
<!--            <div class="map-container">-->
<!--                <div class="map-legend">-->
<!--                    <div class="legend-item"><span class="seat-icon available"></span><span>可预约</span></div>-->
<!--                    <div class="legend-item"><span class="seat-icon occupied"></span><span>已被预约</span></div>-->
<!--                    <div class="legend-item"><span class="seat-icon in-use"></span><span>使用中</span></div>-->
<!--                    <div class="legend-item"><span class="seat-icon temporary-leave"></span><span>暂离中</span></div>-->
<!--                    <div class="legend-item"><span class="seat-icon selected"></span><span>已选择</span></div>-->
<!--                </div>-->
<!--                <div class="map-visualization">-->
<!--                    <div class="seats-container" id="seats-container"></div>-->
<!--                </div>-->
<!--            </div>-->
<!--        </section>-->

<!--        <section class="selected-seat-info">-->
<!--            <div class="info-card">-->
<!--                <h3>选中座位信息</h3>-->
<!--                <div id="selected-seat-details">-->
<!--                    <div class="no-seat-selected">请选择一个座位</div>-->
<!--                    <div class="seat-details" style="display: none;">-->
<!--                        <p><span class="label">座位编号：</span><span id="seat-number">-</span></p>-->
<!--                        <p><span class="label">所在区域：</span><span id="seat-area">-</span></p>-->
<!--                        <p><span class="label">预约时间：</span><span id="booking-time">-</span></p>-->
<!--                        <p><span class="label">状态：</span><span id="seat-status">-</span></p>-->
<!--                    </div>-->
<!--                </div>-->
<!--                <div class="booking-actions">-->
<!--                    <button id="confirm-booking" class="btn btn-primary" disabled>确认预约</button>-->
<!--                    <button id="cancel-selection" class="btn btn-secondary" disabled>取消选择</button>-->
<!--                </div>-->
<!--            </div>-->
<!--        </section>-->
<!--    </div>-->
<!--</main>-->

<!--<script>-->
<!--    const BASE_URL = 'http://localhost:8080/api';-->
<!--    document.addEventListener('DOMContentLoaded', () => {-->
<!--        const user = sessionStorage.getItem('currentUser');-->
<!--        if (!user) {-->
<!--            alert('请先登录');-->
<!--            location.href = 'login.html';-->
<!--            return;-->
<!--        }-->
<!--        loadUserInfo(user);-->

<!--    });-->
<!--    async function loadUserInfo(username) {-->
<!--        try {-->
<!--            const res = await fetch(`${BASE_URL}/user/get-info?username=${username}`);-->
<!--            if (!res.ok) throw new Error('网络异常');-->
<!--            const student = await res.json();-->
<!--            console.log('Student:', JSON.stringify(student, null, 2));-->
<!--            document.getElementById('welcome').textContent = `欢迎，${student.username} 同学`;-->
<!--        } catch (e) {-->
<!--            console.error(e);-->
<!--            alert('加载用户信息失败');-->
<!--        }-->
<!--    }-->
<!--    /* ================= 时间段选择 ================= */-->
<!--    const timeGrid = document.getElementById('time-grid');-->
<!--    const selectedTimeEl = document.getElementById('selected-time');-->
<!--    const timeDurationEl = document.getElementById('time-duration');-->
<!--    const clearTimeBtn = document.getElementById('clear-time');-->

<!--    let selectionState = { start: null, end: null };-->

<!--    function generateTimeSlots() {-->
<!--        timeGrid.innerHTML = '';-->
<!--        const now = new Date(), currentHour = now.getHours();-->
<!--        for (let h = 7; h <= 21; h++) {-->
<!--            const start = `${String(h).padStart(2, '0')}:00`,-->
<!--                end   = `${String(h + 1).padStart(2, '0')}:00`;-->
<!--            const div = document.createElement('div');-->
<!--            div.className = 'time-slot';-->
<!--            div.textContent = `${start}-${end}`;-->
<!--            div.dataset.start = start; div.dataset.end = end; div.dataset.hour = h;-->
<!--            if (h < currentHour) div.classList.add('disabled');-->
<!--            else div.addEventListener('click', () => handleTimeClick(div));-->
<!--            timeGrid.appendChild(div);-->
<!--        }-->
<!--    }-->
<!--    function handleTimeClick(slot) {-->
<!--        const h = parseInt(slot.dataset.hour);-->
<!--        if (selectionState.start === null) {-->
<!--            selectionState.start = h; slot.classList.add('selected');-->
<!--        } else if (selectionState.end === null) {-->
<!--            if (h <= selectionState.start) { alert('结束时间必须在开始时间之后'); return; }-->
<!--            selectionState.end = h;-->
<!--            document.querySelectorAll('.time-slot').forEach(s => {-->
<!--                const hour = parseInt(s.dataset.hour);-->
<!--                if (hour >= selectionState.start && hour <= selectionState.end) s.classList.add('selected');-->
<!--            });-->
<!--        } else { clearTimeSelection(); selectionState.start = h; slot.classList.add('selected'); }-->
<!--        updateTimeSummary(); updateSelectedSeatTime(); updateConfirmButtonState();-->
<!--    }-->
<!--    function clearTimeSelection() {-->
<!--        selectionState = { start: null, end: null };-->
<!--        document.querySelectorAll('.time-slot.selected').forEach(s => s.classList.remove('selected'));-->
<!--        updateTimeSummary(); updateConfirmButtonState();-->
<!--    }-->
<!--    function updateTimeSummary() {-->
<!--        if (selectionState.start === null) { selectedTimeEl.textContent = '&#45;&#45;:&#45;&#45; - &#45;&#45;:&#45;&#45;'; timeDurationEl.textContent = '0'; return; }-->
<!--        const startTime = `${String(selectionState.start).padStart(2, '0')}:00`;-->
<!--        let endTime, duration;-->
<!--        if (selectionState.end === null) { endTime = `${String(selectionState.start + 1).padStart(2, '0')}:00`; duration = 1; }-->
<!--        else { endTime = `${String(selectionState.end + 1).padStart(2, '0')}:00`; duration = selectionState.end - selectionState.start + 1; }-->
<!--        selectedTimeEl.textContent = `${startTime} - ${endTime}`; timeDurationEl.textContent = duration;-->
<!--    }-->
<!--    clearTimeBtn.addEventListener('click', clearTimeSelection);-->

<!--    /* ================= 楼层 & 座位 ================= */-->
<!--    const floorTabs = document.querySelectorAll('.floor-tab');-->
<!--    const seatsContainer = document.getElementById('seats-container');-->
<!--    const floorConfig = {-->
<!--        '1': { name: '1楼-阅览区', seats: 400 },-->
<!--        '2': { name: '2楼-电子阅览区', seats: 600 },-->
<!--        '3': { name: '3楼-考公考研区', seats: 1000 },-->
<!--        '4': { name: '4楼-阅读区', seats: 8 },-->
<!--        '5': { name: '4楼-讨论区', seats: 300 }-->
<!--    };-->
<!--    let selectedSeatGlobal = null;-->

<!--    function generateSeats(floor) {-->
<!--        seatsContainer.innerHTML = '';-->
<!--        const config = floorConfig[floor];-->
<!--        for (let i = 0; i < config.seats; i++) {-->
<!--            const seat = document.createElement('div');-->
<!--            const seatId = (i + 1).toString();-->
<!--            seat.className = 'seat available';-->
<!--            seat.dataset.seat = seatId; seat.dataset.floor = floor;-->
<!--            seat.textContent = seatId;-->
<!--            seat.addEventListener('click', () => handleSeatClick(seat));-->
<!--            seatsContainer.appendChild(seat);-->
<!--        }-->
<!--    }-->
<!--    function handleSeatClick(seat) {-->
<!--        document.querySelectorAll('.seat.selected').forEach(s => s.classList.remove('selected'));-->
<!--        seat.classList.add('selected'); selectedSeatGlobal = seat;-->
<!--        updateSelectedSeatInfo(seat); document.getElementById('cancel-selection').disabled = false;-->
<!--    }-->
<!--    function updateSelectedSeatInfo(seat) {-->
<!--        const seatId = seat.dataset.seat, floor = seat.dataset.floor, floorName = floorConfig[floor].name;-->
<!--        document.getElementById('seat-number').textContent = seatId;-->
<!--        document.getElementById('seat-area').textContent = floorName;-->
<!--        document.getElementById('seat-status').textContent = '可预约';-->
<!--        document.querySelector('.no-seat-selected').style.display = 'none';-->
<!--        document.querySelector('.seat-details').style.display = 'block';-->
<!--        updateSelectedSeatTime(); updateConfirmButtonState();-->
<!--    }-->
<!--    function updateSelectedSeatTime() {-->
<!--        if (!selectedSeatGlobal || selectionState.start === null) { document.getElementById('booking-time').textContent = '请选择时间段'; return; }-->
<!--        const start = `${String(selectionState.start).padStart(2, '0')}:00`;-->
<!--        const end = selectionState.end === null ? `${String(selectionState.start + 1).padStart(2, '0')}:00` : `${String(selectionState.end + 1).padStart(2, '0')}:00`;-->
<!--        document.getElementById('booking-time').textContent = `${start} - ${end}`;-->
<!--    }-->
<!--    function updateConfirmButtonState() {-->
<!--        document.getElementById('confirm-booking').disabled = !(selectedSeatGlobal && selectionState.start !== null);-->
<!--    }-->
<!--    floorTabs.forEach(tab => {-->
<!--        tab.addEventListener('click', function () {-->
<!--            floorTabs.forEach(t => t.classList.remove('active'));-->
<!--            this.classList.add('active');-->
<!--            generateSeats(this.dataset.floor); resetSeatSelection();-->
<!--        });-->
<!--    });-->

<!--    /* ================= 确认预约 ================= */-->
<!--    document.getElementById('confirm-booking').addEventListener('click', () => {-->
<!--        if (!selectedSeatGlobal || selectionState.start === null) return;-->

<!--        const seatId = selectedSeatGlobal.dataset.seat;-->
<!--        const floor = selectedSeatGlobal.dataset.floor;-->
<!--        const floorName = floorConfig[floor].name;-->

<!--        const startTime = `${String(selectionState.start).padStart(2, '0')}:00`;-->
<!--        const endTime = selectionState.end === null ? `${String(selectionState.start + 1).padStart(2, '0')}:00` : `${String(selectionState.end + 1).padStart(2, '0')}:00`;-->

<!--        /* ===== 时间段重叠检查 ===== */-->
<!--        const currentBooking = JSON.parse(localStorage.getItem('currentBooking')) || null;-->
<!--        if (currentBooking && currentBooking.exists) {-->
<!--            const toMin = t => { const [h, m] = t.split(':').map(Number); return h * 60 + m; };-->
<!--            const newStart = toMin(startTime), newEnd = toMin(endTime);-->
<!--            const oldStart = toMin(currentBooking.startTime), oldEnd = toMin(currentBooking.endTime);-->
<!--            const isOverlap = !(newEnd <= oldStart || newStart >= oldEnd);-->
<!--            if (isOverlap) { alert('您在该时段已有预约，无法重复预约！'); return; }-->
<!--        }-->

<!--        const bookingInfo = {-->
<!--            exists: true,-->
<!--            status: 'pending',-->
<!--            seatId, floor, floorName, startTime, endTime,-->
<!--            date: new Date().toISOString().slice(0, 10),-->
<!--            user: '张三'-->
<!--        };-->
<!--        localStorage.setItem('currentBooking', JSON.stringify(bookingInfo));-->
<!--        addToHistory(bookingInfo);-->

<!--        selectedSeatGlobal.classList.remove('selected');-->
<!--        selectedSeatGlobal.classList.add('occupied');-->
<!--        selectedSeatGlobal.style.cursor = 'not-allowed';-->
<!--        alert(`预约成功！\n座位：${seatId}\n时间：${startTime} - ${endTime}`);-->
<!--        resetSeatSelection(); clearTimeSelection();-->
<!--    });-->

<!--    function addToHistory(booking) {-->
<!--        let history = JSON.parse(localStorage.getItem('historyBookings')) || [];-->
<!--        history.unshift({ ...booking, bookingTime: new Date().toISOString() });-->
<!--        localStorage.setItem('historyBookings', JSON.stringify(history));-->
<!--    }-->

<!--    /* ================= 取消选择 ================= */-->
<!--    document.getElementById('cancel-selection').addEventListener('click', resetSeatSelection);-->
<!--    function resetSeatSelection() {-->
<!--        document.querySelectorAll('.seat.selected').forEach(s => s.classList.remove('selected'));-->
<!--        selectedSeatGlobal = null;-->
<!--        document.querySelector('.no-seat-selected').style.display = 'block';-->
<!--        document.querySelector('.seat-details').style.display = 'none';-->
<!--        updateConfirmButtonState(); document.getElementById('cancel-selection').disabled = true;-->
<!--    }-->

<!--    /* ================= 初始化 ================= */-->
<!--    generateTimeSlots();-->
<!--    generateSeats('1');-->
<!--</script>-->
<!--</body>-->
<!--</html>-->


<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图书馆座位预约系统 - 座位选择</title>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
        }
        body {
            background-color: #f0f8ff;
            min-height: 100vh;
            color: #333;
            display: flex;
            flex-direction: column;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            flex: 1;
        }
        .main-header {
            background-color: rgba(255, 255, 255, 0.95);
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            padding: 15px 0;
        }
        .header-container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .logo {
            display: flex;
            align-items: center;
            gap: 10px;
            font-size: 1.5rem;
            font-weight: bold;
            color: #1a2a6c;
        }
        .main-nav ul {
            display: flex;
            list-style: none;
            gap: 20px;
        }
        .main-nav a {
            text-decoration: none;
            color: #333;
            padding: 8px 15px;
            border-radius: 5px;
            transition: background-color 0.3s;
        }
        .main-nav a:hover, .main-nav li.active a {
            background-color: #1a73e8;
            color: white;
        }
        .user-info {
            display: flex;
            align-items: center;
            gap: 15px;
        }
        .welcome {
            font-weight: 500;
        }
        .main-content {
            flex: 1;
            padding: 20px 0;
        }
        .selection-header {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
        }
        .selection-header h1 {
            color: #1a2a6c;
            margin-bottom: 20px;
            font-size: 2rem;
        }
        .time-selector label {
            font-weight: 500;
            color: #1a2a6c;
            font-size: 1.1rem;
        }
        .time-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 10px;
            margin: 15px 0;
        }
        .time-slot {
            padding: 12px 8px;
            border: 1px solid #ddd;
            border-radius: 5px;
            text-align: center;
            cursor: pointer;
            transition: all 0.2s;
            background-color: #f8f9fa;
        }
        .time-slot:hover {
            background-color: #e9ecef;
        }
        .time-slot.selected {
            background-color: #1a73e8;
            color: white;
            border-color: #1a73e8;
        }
        .time-slot.disabled {
            background-color: #f8f9fa;
            color: #adb5bd;
            cursor: not-allowed;
            opacity: 0.6;
        }
        .time-summary {
            margin-top: 15px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
            text-align: center;
        }
        .time-summary p {
            margin-bottom: 5px;
        }
        .time-controls button {
            padding: 8px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            background-color: white;
            cursor: pointer;
            transition: all 0.2s;
        }
        .time-controls button:hover {
            background-color: #f1f3f4;
        }
        .floor-selector {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 30px;
        }
        .floor-tabs {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .floor-tab {
            padding: 12px 20px;
            background-color: #f1f3f4;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            display: flex;
            flex-direction: column;
            align-items: center;
            text-align: center;
            min-width: 120px;
        }
        .floor-tab.active {
            background-color: #1a73e8;
            color: white;
        }
        .floor-tab:hover:not(.active) {
            background-color: #e0e0e0;
        }
        .floor-name {
            font-size: 1.1rem;
            font-weight: 600;
        }
        .floor-desc {
            font-size: 0.85rem;
            margin-top: 5px;
            opacity: 0.8;
        }
        .seat-map {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
        }
        .map-legend {
            display: flex;
            gap: 20px;
            flex-wrap: wrap;
            margin-bottom: 20px;
        }
        .legend-item {
            display: flex;
            align-items: center;
            gap: 8px;
        }
        .seat-icon {
            width: 20px;
            height: 20px;
            border-radius: 4px;
        }
        .seat-icon.available {
            background-color: #50c878;
        }
        .seat-icon.reserved {
            background-color: #e74c3c;
        }
        .seat-icon.occupied {
            background-color: #f39c12;
        }
        .seat-icon.away {
            background-color: #17a2b8;
        }
        .seat-icon.selected {
            background-color: #1a73e8;
        }
        .seat-grid {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        .map-visualization {
            position: relative;
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            min-height: 400px;
        }
        .seats-container {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(50px, 1fr));
            gap: 10px;
            margin-top: 20px;
        }
        .seat {
            width: 40px;
            height: 40px;
            border-radius: 6px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 0.8rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }
        .seat.available {
            background-color: #50c878;
            color: white;
        }
        .seat.reserved {
            background-color: #e74c3c;
            color: white;
            cursor: not-allowed;
        }
        .seat.selected {
            background-color: #1a73e8;
            color: white;
            transform: scale(1.1);
        }
        .seat.occupied {
            background-color: #f39c12;
            color: white;
            cursor: not-allowed;
        }
        .seat.away {
            background-color: #17a2b8;
            color: white;
            cursor: not-allowed;
        }
        .seat.available:hover:not(.selected) {
            background-color: #40b868;
            transform: translateY(-2px);
        }
        .selected-seat-info {
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 12px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
        }
        .info-card h3 {
            color: #1a2a6c;
            margin-bottom: 20px;
            font-size: 1.5rem;
        }
        .seat-details {
            background-color: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .seat-details p {
            margin-bottom: 10px;
            display: flex;
            justify-content: space-between;
        }
        .seat-details .label {
            font-weight: 500;
            color: #1a2a6c;
        }
        .no-seat-selected {
            text-align: center;
            color: #7f8c8d;
            font-style: italic;
            padding: 30px 0;
        }
        .booking-actions {
            display: flex;
            gap: 15px;
        }
        .btn {
            padding: 12px 25px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.3s;
            flex: 1;
            font-size: 1rem;
        }
        .btn-primary {
            background: #1a73e8;
            color: white;
        }
        .btn-primary:hover:not(:disabled) {
            background: #0d62d9;
        }
        .btn-secondary {
            background: #f1f3f4;
            color: #333;
        }
        .btn-secondary:hover {
            background: #e0e0e0;
        }
        .btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        @media (max-width: 768px) {
            .header-container {
                flex-direction: column;
                gap: 15px;
            }
            .main-nav ul {
                flex-wrap: wrap;
                justify-content: center;
            }
            .user-info {
                flex-direction: column;
                gap: 10px;
            }
            .selection-controls {
                flex-direction: column;
                gap: 15px;
            }
            .time-grid {
                grid-template-columns: repeat(2, 1fr);
            }
            .floor-tabs {
                flex-direction: column;
            }
            .floor-tab {
                width: 100%;
            }
            .seats-container {
                justify-content: center;
            }
            .booking-actions {
                flex-direction: column;
            }
        }
        .loading-overlay {
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(255, 255, 255, 0.8);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            border-radius: 8px;
        }
        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #1a73e8;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        .error-message {
            color: #e74c3c;
            text-align: center;
            padding: 20px;
            background: #ffeaea;
            border-radius: 5px;
            margin: 10px 0;
        }
        .success-message {
            color: #28a745;
            text-align: center;
            padding: 10px;
            background: #e8ffe8;
            border-radius: 5px;
            margin: 10px 0;
            display: none;
        }
        .floor-info {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
        }
        .floor-stats {
            display: flex;
            gap: 15px;
            font-size: 0.9rem;
        }
        .stat-item {
            display: flex;
            align-items: center;
            gap: 5px;
        }
    </style>
</head>
<body>
<header class="main-header">
    <div class="header-container">
        <div class="logo"><i class="fa fa-book"></i><span>图书馆座位预约系统</span></div>
        <nav class="main-nav">
            <ul>
                <li><a href="index.html">首页</a></li>
                <li class="active"><a href="seat-selection.html">座位选择</a></li>
                <li><a href="booking-management.html">预约查询</a></li>
                <li><a href="user-profile.html">个人中心</a></li>
            </ul>
        </nav>
        <div class="user-info">
            <span class="welcome" id="welcome">欢迎，加载中...</span>
            <button class="btn btn-secondary" onclick="logout()" style="margin-left: 10px; padding: 5px 10px; font-size: 0.8rem;">退出</button>
        </div>
    </div>
</header>

<main class="main-content">
    <div class="container">
        <section class="selection-header">
            <h1>座位选择</h1>
            <div class="selection-controls">
                <div class="time-selector">
                    <label>选择时间段：</label>
                    <div class="time-grid" id="time-grid"></div>
                    <div class="time-summary">
                        <p class="hint">点击选择开始时间和结束时间</p>
                        <p id="time-range-display">已选择：<span id="selected-time">--:-- - --:--</span> 共 <span id="time-duration">0</span> 小时</p>
                        <div class="time-controls">
                            <button id="clear-time">清空选择</button>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="floor-selector">
            <div class="floor-tabs">
                <button class="floor-tab active" data-floor="1"><span class="floor-name">1楼-阅览区</span><span class="floor-desc">400个座位</span></button>
                <button class="floor-tab" data-floor="2"><span class="floor-name">2楼-电子阅览区</span><span class="floor-desc">600个座位</span></button>
                <button class="floor-tab" data-floor="3"><span class="floor-name">3楼-考公考研区</span><span class="floor-desc">1000个座位</span></button>
                <button class="floor-tab" data-floor="4"><span class="floor-name">4楼-阅读区</span><span class="floor-desc">8个座位</span></button>
                <button class="floor-tab" data-floor="5"><span class="floor-name">4楼-讨论区</span><span class="floor-desc">300个座位</span></button>
            </div>
        </section>

        <section class="seat-map">
            <div class="map-container">
                <div class="map-legend">
                    <div class="legend-item"><span class="seat-icon available"></span><span>可预约</span></div>
                    <div class="legend-item"><span class="seat-icon reserved"></span><span>已被预约</span></div>
                    <div class="legend-item"><span class="seat-icon occupied"></span><span>使用中</span></div>
                    <div class="legend-item"><span class="seat-icon away"></span><span>暂离中</span></div>
                    <div class="legend-item"><span class="seat-icon selected"></span><span>已选择</span></div>
                </div>
                <div class="floor-info">
                    <div class="floor-stats">
                        <div class="stat-item"><span class="seat-icon available"></span><span id="available-count">0</span> 可预约</div>
                        <div class="stat-item"><span class="seat-icon reserved"></span><span id="reserved-count">0</span> 已预约</div>
                        <div class="stat-item"><span class="seat-icon occupied"></span><span id="occupied-count">0</span> 使用中</div>
                        <div class="stat-item"><span class="seat-icon away"></span><span id="away-count">0</span> 暂离中</div>
                    </div>
                </div>
                <div class="map-visualization" id="map-visualization">
                    <div class="seats-container" id="seats-container"></div>
                    <div class="loading-overlay" id="loading-overlay" style="display: none;">
                        <div class="spinner"></div>
                    </div>
                </div>
            </div>
        </section>

        <section class="selected-seat-info">
            <div class="info-card">
                <h3>选中座位信息</h3>
                <div id="selected-seat-details">
                    <div class="no-seat-selected">请选择一个座位</div>
                    <div class="seat-details" style="display: none;">
                        <p><span class="label">座位编号：</span><span id="seat-number">-</span></p>
                        <p><span class="label">所在区域：</span><span id="seat-area">-</span></p>
                        <p><span class="label">座位ID：</span><span id="seat-id">-</span></p>
                        <p><span class="label">预约时间：</span><span id="booking-time">-</span></p>
                        <p><span class="label">状态：</span><span id="seat-status">-</span></p>
                    </div>
                </div>
                <div class="booking-actions">
                    <button id="confirm-booking" class="btn btn-primary" disabled>确认预约</button>
                    <button id="cancel-selection" class="btn btn-secondary" disabled>取消选择</button>
                </div>
            </div>
        </section>
    </div>
</main>

<script>
    const BASE_URL = 'http://localhost:8080/api';
    let currentFloor = '1';
    let seatsData = {};

    document.addEventListener('DOMContentLoaded', () => {
        const user = sessionStorage.getItem('currentUser');
        if (!user) {
            alert('请先登录');
            location.href = 'login.html';
            return;
        }
        loadUserInfo(user);
        generateTimeSlots();
        loadSeatsData('1'); // 默认加载1楼座位数据
    });

    async function loadUserInfo(username) {
        try {
            const res = await fetch(`${BASE_URL}/user/get-info?username=${username}`);
            if (!res.ok) throw new Error('网络异常');
            const student = await res.json();
            document.getElementById('welcome').textContent = `欢迎，${student.username} 同学`;
        } catch (e) {
            console.error(e);
            alert('加载用户信息失败');
        }
    }

    /* ================= 时间段选择 ================= */
    const timeGrid = document.getElementById('time-grid');
    const selectedTimeEl = document.getElementById('selected-time');
    const timeDurationEl = document.getElementById('time-duration');
    const clearTimeBtn = document.getElementById('clear-time');

    let selectionState = { start: null, end: null };


    function generateTimeSlots() {
        timeGrid.innerHTML = '';
        const now = new Date(), currentHour = now.getHours();
        for (let h = 7; h <= 21; h++) {
            const start = `${String(h).padStart(2, '0')}:00`,
                end   = `${String(h + 1).padStart(2, '0')}:00`;
            const div = document.createElement('div');
            div.className = 'time-slot';
            div.textContent = `${start}-${end}`;
            div.dataset.start = start; div.dataset.end = end; div.dataset.hour = h;
            if (h < currentHour) div.classList.add('disabled');
            else div.addEventListener('click', () => handleTimeClick(div));
            timeGrid.appendChild(div);
        }
    }

    function handleTimeClick(slot) {
        const h = parseInt(slot.dataset.hour);
        if (selectionState.start === null) {
            selectionState.start = h; slot.classList.add('selected');
        } else if (selectionState.end === null) {
            if (h <= selectionState.start) { alert('结束时间必须在开始时间之后'); return; }
            selectionState.end = h;
            document.querySelectorAll('.time-slot').forEach(s => {
                const hour = parseInt(s.dataset.hour);
                if (hour >= selectionState.start && hour <= selectionState.end) s.classList.add('selected');
            });
        } else { clearTimeSelection(); selectionState.start = h; slot.classList.add('selected'); }
        updateTimeSummary(); updateSelectedSeatTime(); updateConfirmButtonState();
    }

    function clearTimeSelection() {
        selectionState = { start: null, end: null };
        document.querySelectorAll('.time-slot.selected').forEach(s => s.classList.remove('selected'));
        updateTimeSummary(); updateConfirmButtonState();
    }

    function updateTimeSummary() {
        if (selectionState.start === null) { selectedTimeEl.textContent = '--:-- - --:--'; timeDurationEl.textContent = '0'; return; }
        const startTime = `${String(selectionState.start).padStart(2, '0')}:00`;
        let endTime, duration;
        if (selectionState.end === null) { endTime = `${String(selectionState.start + 1).padStart(2, '0')}:00`; duration = 1; }
        else { endTime = `${String(selectionState.end + 1).padStart(2, '0')}:00`; duration = selectionState.end - selectionState.start + 1; }
        selectedTimeEl.textContent = `${startTime} - ${endTime}`; timeDurationEl.textContent = duration;
    }

    clearTimeBtn.addEventListener('click', clearTimeSelection);

    /* ================= 楼层 & 座位 ================= */
    const floorTabs = document.querySelectorAll('.floor-tab');
    const seatsContainer = document.getElementById('seats-container');
    const loadingOverlay = document.getElementById('loading-overlay');

    const floorConfig = {
        '1': { name: '1楼-阅览区', area: '1'  ,columns: 20 },
        '2': { name: '2楼-电子阅览区', area: '2' },
        '3': { name: '3楼-考公考研区', area: '3' },
        '4': { name: '4楼-阅读区', area: '4', columns: 4 },
        '5': { name: '4楼-讨论区', area: '5', columns: 15 }
    };

    let selectedSeatGlobal = null;

    // 从后端加载座位数据
    async function loadSeatsData(floor) {
        try {
            loadingOverlay.style.display = 'flex';
            const area = floorConfig[floor].area;
            const res = await fetch(`${BASE_URL}/seat/area/${area}`);
            if (!res.ok) throw new Error('获取座位数据失败');

            const seats = await res.json();
            // 调试信息
            console.log(`楼层 ${floor} 座位数据:`, seats.map(s => ({id: s.id, number: s.seatNumber, status: s.baseStatus})));

            seatsData[floor] = seats;
            generateSeats(floor);
            updateFloorStats(seats);
        } catch (e) {
            console.error('加载座位数据失败:', e);
            alert('加载座位数据失败，请稍后重试');
        } finally {
            loadingOverlay.style.display = 'none';
        }
    }

    // 生成座位显示
    function generateSeats(floor) {
        seatsContainer.innerHTML = '';
        const seats = seatsData[floor] || [];

        // 按座位编号排序 - 解决乱序问题
        seats.sort((a, b) => {
            // 将座位编号转换为数字进行比较
            const numA = parseInt(a.seatNumber) || 0;
            const numB = parseInt(b.seatNumber) || 0;
            return numA - numB;
        });
        // 设置网格列数
        const columns = floorConfig[floor].columns || 20;
        seatsContainer.style.gridTemplateColumns = `repeat(${columns}, 40px)`;
        seats.forEach(seat => {
            const seatElement = document.createElement('div');
            seatElement.className = `seat ${getStatusClass(seat.baseStatus)}`;
            seatElement.dataset.seatId = seat.id;
            seatElement.dataset.seatNumber = seat.seatNumber;
            seatElement.dataset.floor = floor;
            seatElement.dataset.status = seat.baseStatus;
            seatElement.textContent = seat.seatNumber;

            // 只有可预约的座位才能点击
            if (seat.baseStatus === 'AVAILABLE') {
                seatElement.addEventListener('click', () => handleSeatClick(seatElement));
            } else {
                seatElement.style.cursor = 'not-allowed';
            }

            seatsContainer.appendChild(seatElement);
        });
    }

    // 根据后端状态获取对应的CSS类名
    function getStatusClass(status) {
        const statusMap = {
            'AVAILABLE': 'available',
            'RESERVED': 'reserved',
            'OCCUPIED': 'occupied',
            'AWAY': 'away'
        };
        return statusMap[status] || 'available';
    }

    // 获取状态对应的中文描述
    function getStatusText(status) {
        const statusMap = {
            'AVAILABLE': '可预约',
            'RESERVED': '已被预约',
            'OCCUPIED': '使用中',
            'AWAY': '暂离中'
        };
        return statusMap[status] || '未知状态';
    }

    // 更新楼层统计信息
    function updateFloorStats(seats) {
        const stats = {
            available: 0,
            reserved: 0,
            occupied: 0,
            away: 0
        };

        seats.forEach(seat => {
            const statusClass = getStatusClass(seat.baseStatus);
            if (stats[statusClass] !== undefined) {
                stats[statusClass]++;
            }
        });

        document.getElementById('available-count').textContent = stats.available;
        document.getElementById('reserved-count').textContent = stats.reserved;
        document.getElementById('occupied-count').textContent = stats.occupied;
        document.getElementById('away-count').textContent = stats.away;
    }

    function handleSeatClick(seat) {
        // 只有可预约的座位才能被选择
        if (seat.dataset.status !== 'AVAILABLE') {
            alert('该座位当前不可预约');
            return;
        }

        document.querySelectorAll('.seat.selected').forEach(s => s.classList.remove('selected'));
        seat.classList.add('selected');
        selectedSeatGlobal = seat;
        updateSelectedSeatInfo(seat);
        document.getElementById('cancel-selection').disabled = false;
    }

    function updateSelectedSeatInfo(seat) {
        const seatNumber = seat.dataset.seatNumber;
        const floor = seat.dataset.floor;
        const seatId = seat.dataset.seatId;
        const floorName = floorConfig[floor].name;
        const status = getStatusText(seat.dataset.status);

        document.getElementById('seat-number').textContent = seatNumber;
        document.getElementById('seat-area').textContent = floorName;
        document.getElementById('seat-id').textContent = seatId;
        document.getElementById('seat-status').textContent = status;

        document.querySelector('.no-seat-selected').style.display = 'none';
        document.querySelector('.seat-details').style.display = 'block';
        updateSelectedSeatTime();
        updateConfirmButtonState();
    }

    function updateSelectedSeatTime() {
        if (!selectedSeatGlobal || selectionState.start === null) {
            document.getElementById('booking-time').textContent = '请选择时间段';
            return;
        }
        const start = `${String(selectionState.start).padStart(2, '0')}:00`;
        const end = selectionState.end === null ?
            `${String(selectionState.start + 1).padStart(2, '0')}:00` :
            `${String(selectionState.end + 1).padStart(2, '0')}:00`;
        document.getElementById('booking-time').textContent = `${start} - ${end}`;
    }

    function updateConfirmButtonState() {
        document.getElementById('confirm-booking').disabled = !(selectedSeatGlobal && selectionState.start !== null);
    }

    // 楼层切换事件
    floorTabs.forEach(tab => {
        tab.addEventListener('click', function () {
            const floor = this.dataset.floor;
            floorTabs.forEach(t => t.classList.remove('active'));
            this.classList.add('active');
            currentFloor = floor;
            loadSeatsData(floor);
            resetSeatSelection();
        });
    });

    /* ================= 确认预约 ================= */
    document.getElementById('confirm-booking').addEventListener('click', async () => {
        if (!selectedSeatGlobal || selectionState.start === null) return;

        const seatId = selectedSeatGlobal.dataset.seatId;
        const seatNumber = selectedSeatGlobal.dataset.seatNumber;
        const floor = selectedSeatGlobal.dataset.floor;
        const floorName = floorConfig[floor].name;
        const username = sessionStorage.getItem('currentUser');

        // 修正时间格式：只发送时间部分，不包含日期
        const startTime = `${String(selectionState.start).padStart(2, '0')}:00:00`;
        const endTime = selectionState.end === null ?
            `${String(selectionState.start + 1).padStart(2, '0')}:00:00` :
            `${String(selectionState.end + 1).padStart(2, '0')}:00:00`;

        // 获取今天的日期
        const today = new Date().toISOString().split('T')[0];

        // 构造预约请求
        const reservationRequest = {
            seatId: parseInt(seatId),
            username: username,
            date: today,  // 单独的日期字段
            startTime: startTime,  // 纯时间格式：HH:mm:ss
            endTime: endTime,      // 纯时间格式：HH:mm:ss
            durationHours: selectionState.end === null ? 1 : (selectionState.end - selectionState.start + 1)
        };

        try {
            const response = await fetch(`${BASE_URL}/seat/reserve`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(reservationRequest)
            });

            if (!response.ok) {
                const errorMsg = await response.text();
                throw new Error(errorMsg);
            }

            const reservationId = await response.text();

            // 预约成功，更新UI
            selectedSeatGlobal.classList.remove('selected', 'available');
            selectedSeatGlobal.classList.add('reserved');
            selectedSeatGlobal.dataset.status = 'RESERVED';
            selectedSeatGlobal.style.cursor = 'not-allowed';

            alert(`预约成功！\n座位：${seatNumber}\n时间：${startTime} - ${endTime}\n预约ID：${reservationId}`);
            resetSeatSelection();
            clearTimeSelection();

            // 刷新座位数据
            loadSeatsData(currentFloor);

        } catch (error) {
            console.error('预约失败:', error);
            alert(`预约失败: ${error.message}`);
        }
    });

    /* ================= 取消选择 ================= */
    document.getElementById('cancel-selection').addEventListener('click', resetSeatSelection);

    function resetSeatSelection() {
        document.querySelectorAll('.seat.selected').forEach(s => s.classList.remove('selected'));
        selectedSeatGlobal = null;
        document.querySelector('.no-seat-selected').style.display = 'block';
        document.querySelector('.seat-details').style.display = 'none';
        updateConfirmButtonState();
        document.getElementById('cancel-selection').disabled = true;
    }

    // 退出登录
    function logout() {
        sessionStorage.removeItem('currentUser');
        location.href = 'login.html';
    }
</script>
</body>
</html>